package scatter.tools.rest.cron.controller;

import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.controller.SuperController;
import scatter.tools.rest.ToolsConfiguration;
import scatter.tools.pojo.cron.form.CronQueryForm;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangwei
 * Created at 2021/2/5 17:46
 */
@Api(tags = "Cron相关接口")
@RestController
@RequestMapping(ToolsConfiguration.CONTROLLER_BASE_PATH + "/cron")
public class CronController extends SuperController {

    @ApiOperation("获取cron的执行时间")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryById(@Validated CronQueryForm cronQueryForm) {
        LocalDateTime next = cronQueryForm.getStartAt();
        if (next == null) {
            next =  LocalDateTime.now();
        }
        List<String> result = new ArrayList<>(cronQueryForm.getTimes());

        CronExpression parse = CronExpression.parse(cronQueryForm.getCronExpression());
        for (int i = 0; i < cronQueryForm.getTimes(); i++) {
            next = parse.next(next);
            result.add(DateUtil.format(next, "yyyy-MM-dd HH:mm:ss"));
        }
        return result;
    }

}
